package com.ycz.sas.jgen.ui;


import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;

import com.ycz.sas.jgen.domain.TableModel;
import com.ycz.sas.jgen.handler.FtpOprate;

import net.sf.jftp.net.BasicConnection;

public class FtpDialogUI extends JDialog{

	private FtpOprate ftpOprate = new FtpOprate();

	private String defaultPath;

	private FtpConfigPanel pnlFtpConfig;

	private TableModel model;
	private JTable table;

	private JButton btnAddFile;
	private JButton btnAddCurrFile;
	private JButton btnTransmit;
	private JButton btnReset;

	public FtpDialogUI(JFrame owner, boolean modal, String defaultPath){
		super(owner, modal);
		this.defaultPath = defaultPath;

		initLayout();
	}

	@Override
	public String getTitle() {
		return "FTP JAR传输";
	}

	protected void initLayout(){
		setSize(465, 525);
		setResizable(false);
		Container contentPane = getContentPane();

		JTabbedPane tabPane = new JTabbedPane();
		contentPane.add(tabPane,"Center");

		pnlFtpConfig = new FtpConfigPanel(this);
		JPanel pnlFileSelector = new JPanel();
		tabPane.add(pnlFileSelector);
		tabPane.add(pnlFtpConfig);
		tabPane.setTitleAt(tabPane.indexOfComponent(pnlFileSelector), "File Selector");
		tabPane.setTitleAt(tabPane.indexOfComponent(pnlFtpConfig), "Ftp Config");
		tabPane.setSelectedComponent(pnlFileSelector);

		model = new TableModel( new String[] { "JAR File", "Dest Dir", "Status" });
		table = new JTable(model);
		setTableType(table);

		btnAddFile = new JButton("添加文件");
		btnAddCurrFile = new JButton("添加Current文件");
		btnTransmit = new JButton("上传");
		btnReset = new JButton("重置");

		JScrollPane spnl = new JScrollPane();
		spnl.setViewportView(table);
		pnlFileSelector.add(spnl);
		pnlFileSelector.add(btnAddFile);
		pnlFileSelector.add(btnAddCurrFile);
		pnlFileSelector.add(btnTransmit);
		pnlFileSelector.add(btnReset);

		btnAddFile.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				actionAddLine();
			}
		});
		btnAddCurrFile.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				actionAddCurrentFile();
			}

		});
		btnTransmit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				actionTransmit();
			}
		});
		btnReset.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				actionReset();
			}
		});
	}

	protected void actionAddLine(){
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(new FileFilter() {

			@Override
			public String getDescription() {
				String strFileDesc = "Jar File(*.jar)";
				return strFileDesc;
			}

			@Override
			public boolean accept(File file) {
				String strFileExt = ".jar";
				if(file.isDirectory() || file.getName().endsWith(strFileExt))
					return true;
				else
					return false;
			}
		});
		chooser.setAcceptAllFileFilterUsed(false);
		chooser.setMultiSelectionEnabled(true);
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setDialogTitle("选择Jar文件");
		chooser.setCurrentDirectory(new File(defaultPath));
		int ok = chooser.showDialog(this, "ADD");
		if (ok == JFileChooser.OPEN_DIALOG) {
			File[] jarFiles = chooser.getSelectedFiles();
			for(File file : jarFiles){
				String filename = file.getAbsolutePath();
				insertLine(filename);
			}
		}
	}

	protected void actionAddCurrentFile(){
		File currFile = new File(defaultPath);

		loopCurrent(currFile);
	}

	private void loopCurrent(File currFile){
		for(File file : currFile.listFiles()){
			if(file.isDirectory()){
				loopCurrent(file);
			} else {
				String filename = file.getAbsolutePath();
				insertLine(filename);
			}
		}
	}

	private void insertLine(String jarFilePath){
		if (!model.containRow(jarFilePath)) {
			model.addRow(new String[]{jarFilePath, getDynamicDestDir(jarFilePath), ""});
			table.updateUI();
		}
	}

	protected void actionTransmit(){
		if(model.getRowCount() <= 0){
			JOptionPane.showMessageDialog(this, "请选择至少一个Jar文件");
			return;
		}
		BasicConnection con = pnlFtpConfig.getConnect();
		String eashome = pnlFtpConfig.getEASHome();
		for (int i = 0, len = model.getRowCount(); i < len; i++) {
			String col0 = (String) model.getValueAt(i, 0);
			String col1 = (String) model.getValueAt(i, 1);
			String[] dests = col1.split(";");
			String srcDir = col0.substring(0, col0.lastIndexOf("\\") + 1);
			for(String dest: dests){
				String destDir = eashome + dest;
				String file = col0.substring(col0.lastIndexOf("\\") + 1);
				boolean isSuccess = ftpOprate.ftpUpload(con, srcDir, destDir, file);
				String oldvalue = (String) model.getValueAt(i, 2);
				if(isSuccess){
					model.setValueAt(oldvalue + "O", i, 2);
				} else {
					model.setValueAt(oldvalue + "X", i, 2);
				}

				table.updateUI();
			}
		}

	}

	protected void actionReset(){
		removeAll();
	}

	private String getDynamicDestDir(String localfile){
		if(localfile.endsWith("-client.jar") || localfile.endsWith("client\\eas_sp.jar"))
			return "/eas/server/deploy/fileserver.ear/easWebClient/lib/sp/";
		if(localfile.endsWith("-server.jar") || localfile.endsWith("server\\eas_sp.jar"))
			return "/eas/server/lib/sp/";
		if(localfile.endsWith("sp-bim-metas.jar"))
			return "/eas/server/metas/;/eas/server/deploy/fileserver.ear/easWebClient/metas/";
		if(localfile.endsWith("-metas.jar") && !localfile.endsWith("sp-bim-metas.jar"))
			return "/eas/server/metas/sp/;/eas/server/deploy/fileserver.ear/easWebClient/metas/sp/";
		return null;
	}

	public void removeAll() {
		model.removeRows(0, model.getRowCount());
		table.updateUI();
	}

	public void setTableType(JTable table){
		table.setEnabled(false);
		table.setGridColor(Color.lightGray);
		table.getColumnModel().getColumn(0).setPreferredWidth(50);
		table.getColumnModel().getColumn(1).setPreferredWidth(190);
		table.getColumnModel().getColumn(2).setPreferredWidth(1);
		table.getTableHeader().setBackground(Color.getHSBColor(221, 221, 230));
	}

	public FtpOprate getFtpOprate(){
		return ftpOprate;
	}

}
